package com.py.credit.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.OrgConstant;
import com.py.credit.entity.Account;
import com.py.credit.entity.Element;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.OrgAccountTableFieldEnum;
import com.py.credit.service.OrgService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "faccount")
@RestController
@RequestMapping(value = "/account")
public class FrontAccountController {
	private final static String FRONT_F_TABLE_ID = "fAccountTableList";

	@Autowired
	private OrgService orgService;

	@ApiOperation(value = "获取机构账号列表", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/getFAccountList.json", method = RequestMethod.POST)
	public RestServiceResult<List<Map<String, Object>>> getBAccountList(
			@ApiParam(required = false, name = "conditions", value = "搜索条件") @RequestParam(required = false) String condition,
			Page page, HttpServletRequest request) {

		List<Map<String, Object>> orgList = new ArrayList<>();

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");
		if (account != null) {

			String[] configColumns = (String[]) MapCache.get(account.getId() + "_" + FRONT_F_TABLE_ID);

			List<String> showColumns = (configColumns == null || configColumns.length == 0)
					? OrgAccountTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

			String[] additionalColumns = { "id", "orgId", "checkType" };

			orgList = orgService.getAccountListByConditionForPage(account.getOrgId(), showColumns, additionalColumns,
					condition, page);

		} else {
			ExceptionLogger.error("AccountController#getFOrgList", "未获取到当前用户信息！");
		}

		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), orgList);

	}

	@ApiOperation(value = "自定义展示列", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/addFColumns.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addFColumns(
			@ApiParam(required = true, name = "columns", value = "展示列数组") @RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");

		if (account != null) {

			MapCache.set(account.getId() + "_" + FRONT_F_TABLE_ID, columns);
		} else {

			ExceptionLogger.error("AccountController#addFColumns", "未获取到当前用户信息！");
		}

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "导出列表", httpMethod = "GET")
	@RequestMapping("/front/fExport.json")
	public void Fexport(
			@ApiParam(required = true, name = "condition", value = "搜索条件") @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@ApiParam(required = true, name = "columnEN", value = "导出列") @RequestParam(value = "columnEN", required = true) String columnEN,
			HttpServletResponse response, HttpServletRequest request, Page page) throws IOException {
		page.setLimit(1000);

		HttpSession session = request.getSession();

		Account account = (Account) session.getAttribute("ACCOUNT");

		if (account != null) {

			List<String> columns = JSONArray.parseArray(columnEN, String.class);

			List<Map<String, Object>> data = orgService.getAccountListByConditionForPage(account.getOrgId(), columns,
					null, condition, page);

			List<OptionalColumn> optionalColumns = OrgAccountTableFieldEnum.getOptionalColumns();

			ExcelUtil.downloadExcel(response, data, "账号列表", "账号列表", columns, optionalColumns);
		} else {
			ExceptionLogger.error("AccountController#fExport", "未获取到当前用户信息！");
		}
	}

	@ApiOperation(value = "获取高级搜索条件", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getAdvancedConditionColumns.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

		return new RestServiceResult<List<OptionalColumn>>(OrgAccountTableFieldEnum.getAdvancedConditionColumns());

	}

	@ApiOperation(value = "获取表头列", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getOptionalColums.json", method = RequestMethod.GET)
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {

		return new RestServiceResult<List<OptionalColumn>>(OrgAccountTableFieldEnum.getOptionalColumns());

	}

	// 主账号权限
	@ApiOperation(value = "冻结账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/suspend.json", method = RequestMethod.POST)
	public RestServiceResult<Object> suspend(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId) {

		orgService.updateAccount(accountId, OrgConstant.ACCOUNT_STATUS_SUSPENDED);

		return new RestServiceResult<Object>();

	}

	// 主账号权限
	@ApiOperation(value = "解冻账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/resume.json", method = RequestMethod.POST)
	public RestServiceResult<Object> resume(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId) {

		orgService.updateAccount(accountId, OrgConstant.ACCOUNT_STATUS_NORMAL);

		return new RestServiceResult<Object>();

	}

	// 主账号权限
	@ApiOperation(value = "删除账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/delete.json", method = RequestMethod.POST)
	public RestServiceResult<Object> delete(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId) {

		// 检验是否是冻结的

		if (orgService.isSuspendedAccount(accountId)) {

			orgService.deleteAccount(accountId);

		} else {

			throw new ServiceException("只能删除冻结账号");

		}

		return new RestServiceResult<Object>();

	}

	// 主账号权限
	@ApiOperation(value = "账号绑定流程节点", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/addAccountAct.json", method = RequestMethod.POST)
	public RestServiceResult<Object> addAccountAct(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId,
			@ApiParam(required = true, name = "checkType", value = "流程节点") @RequestParam(value = "checkType", required = true) String checkType) {

		orgService.addAccountAct(accountId, checkType);

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "获取绑定流程节点", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/getAccountAct.json", method = RequestMethod.GET)
	public RestServiceResult<Object> getAccountAct(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId) {

		List<String> act = orgService.getAccountAct(accountId);

		return new RestServiceResult<Object>(act);

	}

	// 主账号权限
	@ApiOperation(value = "重置账号", httpMethod = "POST", produces = "application/json")
	@RequestMapping(value = "/front/reset.json", method = RequestMethod.POST)
	public RestServiceResult<Object> reset(
			@ApiParam(required = true, name = "accountId", value = "账号编号") @RequestParam(value = "accountId", required = true) String accountId,
			@ApiParam(required = true, name = "password", value = "密码") @RequestParam(value = "password", required = true) String password) {

		orgService.resetAccount(accountId, password);

		return new RestServiceResult<Object>();

	}

	@ApiOperation(value = "详情", httpMethod = "GET", produces = "application/json")
	@RequestMapping(value = "/front/detail.json", method = RequestMethod.GET)
	public RestServiceResult<Object> detail(
			@ApiParam(required = true, name = "orgId", value = "关联机构编号") @RequestParam(value = "orgId", required = true) String orgId) {

		Map<String, Object> result = orgService.getDetail(orgId);

		return new RestServiceResult<Object>(result);

	}

	@ApiOperation(value = "获取系统图", httpMethod = "GET", produces = "image/*")
	@RequestMapping(value = "/front/getSysLogByAccount.png", method = RequestMethod.GET)
	public void getSysLogByAccount(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Account account = (Account) request.getSession().getAttribute("ACCOUNT");

		Element element = orgService.getElement(account.getOrgId());

		byte[] data = orgService.getPic(element.getSysLogo());

		IOUtils.write(data, response.getOutputStream());

	}

	@ApiOperation(value = "获取系统缩略图", httpMethod = "GET", produces = "image/*")
	@RequestMapping(value = "/front/getScaleSysLogByAccount.png", method = RequestMethod.GET)
	public void getScaleSysLogByAccount(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Account account = (Account) request.getSession().getAttribute("ACCOUNT");

		Element element = orgService.getElement(account.getOrgId());

		byte[] data = orgService.getPic(element.getScalingSysLogo());

		IOUtils.write(data, response.getOutputStream());

	}

	@IgnoreAuthority
	@RequestMapping(value = "/front/login.json")
	public RestServiceResult<String> login(@RequestParam(value = "username", required = true) String userName,
			@RequestParam(value = "password", required = true) String password, HttpServletRequest request) {

		Account account = orgService.getAccount(userName, password);

		if (account != null) {

			String status = account.getStatus();

			if ("S".equals(status)) {
				throw new ServiceException("该账号已冻结");
			}

			request.getSession().setAttribute("ACCOUNT", account);

			return new RestServiceResult<String>();

		} else {

			throw new ServiceException("账号密码不正确");

		}

	}

	@IgnoreAuthority
	@RequestMapping(value = "/front/logout.json")
	public RestServiceResult<String> logout(HttpServletRequest request) {

		request.getSession().removeAttribute("ACCOUNT");

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/front/getCurrentUser.json")
	public RestServiceResult<Map<String, String>> getCurrentUser(HttpServletRequest request) {

		Map<String, String> data = new HashMap<>();

		Account account = (Account) request.getSession().getAttribute("ACCOUNT");

		data.put("account", account.getAccount());

		data.put("type", account.getType());

		return new RestServiceResult<Map<String, String>>(data);
	}

}
